using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml;
using octalforty.Componento.ComponentModel.Installation;
using octalforty.Componento.Web.Shared.Data;

namespace octalforty.Componento.Web.Controllers
{
    public class PublishController : Controller
    {
        [Authorize()]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Publish(HttpPostedFileBase manifestFile)
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.Load(manifestFile.InputStream);

            var parser = new ComponentManifestParser();
            var manifest = parser.ParseComponentManifest(xmlDocument);
 
            using(var dataContext = new ComponentoDataContext())
            {
                var profile = (from p in dataContext.Profiles
                               where p.OpenID == User.Identity.Name
                               select p).FirstOrDefault();

                var component = new Component()
                    {
                        Name = manifest.Descriptor.Name,
                        Description = manifest.Descriptor.Description,
                        Version = manifest.Descriptor.Version.ToString(),
                        ProjectUri = manifest.Descriptor.ProjectUri == null ? "" : manifest.Descriptor.ProjectUri.ToString(),
                        ProjectLogoUri = manifest.Descriptor.ProjectLogoUri == null ? "" : manifest.Descriptor.ProjectLogoUri.ToString(),
                        PublishedByProfileID = profile.ID
                    };

                component.ComponentClis.AddRange(
                    manifest.Descriptor.Clis.Select(x => new ComponentCli { Cli = x.Cli.ToString(), Version = x.Version == null ? null : x.Version.ToString(), Component = component }));
                component.ComponentIsas.AddRange(
                    manifest.Descriptor.Isas.Select(x => new ComponentIsa { Isa = x.ToString(), Component = component }));
                component.ComponentLicenses.AddRange(
                    manifest.Descriptor.Licenses.Select(x => new ComponentLicense { License = x, Component = component }));
                component.ComponentManifest = new ComponentManifest { Manifest = xmlDocument.InnerXml, Component = component };

                dataContext.Components.InsertOnSubmit(component);
                dataContext.SubmitChanges();
            } // using

            return RedirectToAction("Index");
        }
    }
}
